#include"list.h"

Listnode* BuyListNode(LTDatatype x)
{
	Listnode* newnode = (Listnode*)malloc(sizeof(Listnode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		exit(-1);
	}
	newnode->data = x;
	newnode->prev = NULL;
	newnode->prev = NULL;
}
Listnode* ListCreat()
{
	Listnode* phead = BuyListNode(-1);
	phead->next = phead;
	phead->prev = phead;
	return phead;
}

void ListDestory(Listnode* phead)
{
	assert(phead);
	assert(phead->next);
	Listnode* cur = phead->next;
	while (cur != phead)
	{
		Listnode* next = cur->next;
		cur->next = NULL;
		cur->prev = NULL;
		free(cur);
		cur = next;
	}
	phead->next = phead;
	phead->prev = phead;
}

void ListPrint(Listnode* phead)
{
	assert(phead);
	Listnode* cur = phead->next;
	while (cur != phead)
	{
		printf("%d ", cur->data);
		cur = cur->next;
	}
	printf("\n");
}

void ListInsert(Listnode* pos, LTDatatype x)
{
	assert(pos);
	Listnode* prev = pos->prev;
	Listnode* newnode = BuyListNode(x);
	prev->next = newnode;
	newnode->prev = prev;
	newnode->next = pos;
	pos->prev = newnode;
}

void ListErase(Listnode* pos)
{
	assert(pos);
	Listnode* prev = pos->prev;
	Listnode* next = pos->next;
	prev->next = next;
	next->prev = prev;
	free(pos);
}

void ListPushFont(Listnode* phead, LTDatatype x)
{
	assert(phead);
	ListInsert(phead->next, x);
}

void ListPushBack(Listnode* phead, LTDatatype x)
{
	assert(phead);
	ListInsert(phead, x);
}

void ListPopFront(Listnode* phead)
{
	assert(phead);
	assert(phead->next);
	ListErase(phead->next);
}
void ListPopBack(Listnode* phead)
{
	assert(phead);
	ListErase(phead->prev);
}

Listnode* ListFind(Listnode* phead, LTDatatype x)
{
	assert(phead);
	assert(phead->next);
	Listnode* cur = phead->next;
	while (cur != phead)
	{
		if (x == cur->data)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}





